package cn.piesat.util;

import java.io.*;

/**
 * properties文件操作工具类
 * @author 奚好雷
 *
 */
public class PropertiesFileUtil {
	
	private File file;
	
	public PropertiesFileUtil(File file) {
		this.file = file;
	}

	public PropertiesFileUtil(String path){
		this(new File(path));
	}
	
	/**
	 * 获取properties文件对象
	 * @return
	 */
	public OrderedPropertiesUtils readPropertiesFile(){
		if(!file.exists()) {
			return null;
		}
		InputStream in = null;
		InputStreamReader isr = null;
		OrderedPropertiesUtils prop = null;
		try {
			in = new FileInputStream(file);
			isr = new InputStreamReader(in, "UTF-8");
			prop = new OrderedPropertiesUtils();
			prop.load(isr);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(isr!=null) {
				try {
					isr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(in!=null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return prop;
	}
	
	/**
	 * 向文件中写入信息
	 * @param prop
	 */
	public void writePropertiesFile(OrderedPropertiesUtils prop){
		OutputStream os = null;
		OutputStreamWriter osw = null;
		try {
			if(this.file.exists() && prop!=null) {
				os = new FileOutputStream(file);
				osw = new OutputStreamWriter(os, "UTF-8");
				prop.store(osw, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}finally {
			if(osw!=null) {
				try {
					osw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(os!=null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 清空文件
	 */
	public void clearFile() {
		FileWriter fileWrite = null;
		if(this.file.exists()) {
			try {
				fileWrite = new FileWriter(file);
				fileWrite.write("");
				fileWrite.flush();
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException();
			}finally {
				if(fileWrite!=null) {
					try {
						fileWrite.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
